package lib.quasar.widget.edit;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputConnectionWrapper;
import android.widget.EditText;

/**
 * description: 有清除功能,只有当有焦点和文本不为空的时候才显示
 * created by kalu on 17-10-17 下午12:10
 */
@SuppressLint("AppCompatCustomView")
public class HanziEditText extends EditText {

    public HanziEditText(Context context) {
        super(context);
    }

    public HanziEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /*****************************************************************************/

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        return new InputWrapper(super.onCreateInputConnection(outAttrs), false);
    }

    private final class InputWrapper extends InputConnectionWrapper implements InputConnection {

        public InputWrapper(InputConnection target, boolean mutable) {
            super(target, mutable);
        }

        @Override
        public boolean commitText(CharSequence text, int newCursorPosition) {

            // 只能输入汉字
            if (!text.toString().matches("[\u4e00-\u9fa5]+")) {
                return false;
            }

            if (null != listener) {
                listener.onInputChange(getText().toString().trim()+text, false);
            }

            return super.commitText(text, newCursorPosition);
        }

        @Override
        public boolean sendKeyEvent(KeyEvent event) {

            if (null != listener && event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
                listener.onInputChange(getText().toString().trim(), false);
            }
            return super.sendKeyEvent(event);
        }
    }

    /*********************************************************************************************/

    private OnInputChangeListener listener;

    public interface OnInputChangeListener {
        void onInputChange(String input, boolean isDelete);
    }

    public void setOnInputChangeListener(OnInputChangeListener listener) {
        this.listener = listener;
    }
}